package com.yf.cmw;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.base.common.bean.AppVersionResult;
import com.base.common.db.model.MachineCacheInfo;
import com.base.common.http.server.MicroHttpServer;
import com.base.common.util.AppTools;
import com.base.common.util.Base64Utils;
import com.base.common.util.DBHelper;
import com.base.common.util.DateUtil;
import com.base.common.util.FileUtil;
import com.base.common.util.IpGetUtil;
import com.base.common.util.ShellUtils;
import com.base.common.util.StringHandler;
import com.base.common.util.StringUtils;

import com.base.common.util.ToastAlert;
import com.base.common.util.ZxingHelper;
import com.yf.cmw.broadcast.AlarmReceiver;
import com.yf.cmw.constant.BussConstant;
import com.yf.cmw.constant.UrlConstantAPI;
import com.yf.cmw.presenter.AsyncCallback;
import com.yf.cmw.presenter.MainPresenter;
import com.yf.cmw.service.TaskService;


import java.io.File;
import java.util.Date;

import static com.yf.cmw.constant.BussConstant.PACKAGE_YF_PLAYER_APP;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AsyncCallback {
    public static final String TAG = "MainActivity";
    //配置ID
    TextView tv_cfgId;
    //App版本号 ：
    EditText txt_appVersion;
    //机器串号：
    EditText txt_mcode;
    //文件路径
    EditText txt_adPath;
    //API地址
    EditText txt_apiServer;
    //心跳间隔：
    EditText txt_minutes;
    //IP地址
    EditText txt_ip;
    //本机访问地址
    TextView local_server_address;
    //发送机器码
    Button btn_sendMcode;
    //机器码二维码
    Button btn_mcodeQrcode;
    //保存配置 ：
    Button btn_save;

    //获取最新配置 ：
    Button btn_pullCfg;

    //议峰光传检查更新 ：
    Button btn_checkUpdate;

    //议峰智播检查更新 ：
    Button btn_checkPlayerUpdate;

    //Wifi  按钮
    Button btn_wifi;

    //广告下载开关
    Button btn_aDswitch;

    //API连接测试
    Button btn_apiTest;
    //下载视频
    Button btn_downLoadVedio;
    //开启服务
    Button btn_startService;
    //删除数据库
    Button btn_delDB;

    //添加广告通知
    Button btn_addAD;

    //删除广告通知
    Button btn_delAD;


    //删除下载日志
    Button btn_delLogs;
    Button btn_delVideo;
    //系统重启
    Button btn_sendReboot;

    //打开播放器
    Button btn_openPlayer;

    //关闭播放器
    Button btn_closePlayer;

    //更新播放器
    Button btn_updatePlayer;

    //更新光传App
    Button btn_updateSpsApp;

    //开启ADB
    Button btn_openADB;

    //定时关机
    Button btn_closeOnTime;
    //多少小时
    EditText txt_onhours;
    //多少分钟
    EditText txt_onminutes;

    TextView tv_result;
    WifiManager wifiManager = null;

    MachineCacheInfo machineCacheInfo;

    DBHelper dbHelper = null;

    MainPresenter mainPresenter = null;

    private ProgressDialog progressDialog;

    // 已生成的机器串码二维码内容
    private String oldMcodeForQrCode;
    // 机器串码弹窗
    private AlertDialog mcodeQrCodeModel;

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case BussConstant.HANDLER_MAIN_FUN_PULLCFG: { //更新配置UI上的最新配置
                    updateUICfgByPull(msg);
                    break;
                }  case BussConstant.HANDLER_CHECK_UPDATE_CONFIRM: { //中的检查更新提示
                    Log.i(TAG,"what = "+msg.what);
                    AppVersionResult appVersionResult = (AppVersionResult)msg.getData().getSerializable("appVersionResult");
                    confirmInstallApk(appVersionResult);
                    break;
                } case BussConstant.HANDLER_APK_DOWNLOAD_PROGRESS: { //中的检查更新提示
                    Log.i(TAG,"what = "+msg.what + ", progress = "+ msg.arg1);
                    progressDialog.incrementProgressBy(msg.arg1);
                    break;
                } case BussConstant.HANDLER_USB_ADS_COPYS: { //USB广告文件复制
                    Log.i(TAG,"what = "+msg.what);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.i(TAG,"读取文件信息!");
                            readFileInfo();
                        }
                    });
                    //readFileInfo();
                    Bundle data = msg.getData();
                    String msgContent = data.getString("msg");
                    if(!StringUtils.isEmpty(msgContent)){
                        tipByLooper(msgContent);
                    }
                    break;
                }
            }
        }
    };


    private void tipByLooper(String msgContent){
        Looper.prepare();
        tip(msgContent);
        Looper.loop();
    }

    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        checkPermission();
        loadData();

        startService();
    }

    /**
     *Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
        super.onResume();
        AlarmReceiver.adSwitch = true;
        readFileInfo();
        copyUsbADS();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        String actionCommand = data.getStringExtra("actionCommand");
        Log.i(TAG, "actionCommand="+actionCommand);
    }

    private void initView() {
        tv_cfgId = findViewById(R.id.tv_cfgId);
        txt_appVersion = findViewById(R.id.txt_appVersion);
        txt_mcode = findViewById(R.id.txt_mcode);
        txt_adPath = findViewById(R.id.txt_adPath);
        txt_apiServer = findViewById(R.id.txt_apiServer);
        txt_minutes = findViewById(R.id.txt_minutes);
        txt_ip = findViewById(R.id.txt_ip);
        local_server_address = findViewById(R.id.local_server_address);
        btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);

        btn_pullCfg = findViewById(R.id.btn_pullCfg);
        btn_pullCfg.setOnClickListener(this);

        btn_checkUpdate = findViewById(R.id.btn_checkUpdate);
        btn_checkUpdate.setOnClickListener(this);

        btn_checkPlayerUpdate = findViewById(R.id.btn_checkPlayerUpdate);
        btn_checkPlayerUpdate.setOnClickListener(this);

        btn_wifi = findViewById(R.id.btn_wifi);
        btn_wifi.setOnClickListener(this);

        btn_aDswitch = findViewById(R.id.btn_aDswitch);
        btn_aDswitch.setOnClickListener(this);

        btn_apiTest = findViewById(R.id.btn_apiTest);
        btn_apiTest.setOnClickListener(this);

        btn_downLoadVedio = findViewById(R.id.btn_downLoadVedio);
        btn_downLoadVedio.setOnClickListener(this);

        btn_startService = findViewById(R.id.btn_startService);
        btn_startService.setOnClickListener(this);

        btn_delDB = findViewById(R.id.btn_delDB);
        btn_delDB.setOnClickListener(this);

        btn_addAD = findViewById(R.id.btn_addAD);
        btn_addAD.setOnClickListener(this);

        btn_delAD = findViewById(R.id.btn_delAD);
        btn_delAD.setOnClickListener(this);

        btn_delLogs = findViewById(R.id.btn_delLogs);
        btn_delLogs.setOnClickListener(this);

        btn_delVideo = findViewById(R.id.btn_delVideo);
        btn_delVideo.setOnClickListener(this);


        btn_sendMcode = findViewById(R.id.btn_sendMcode);
        btn_sendMcode.setOnClickListener(this);

        btn_mcodeQrcode = findViewById(R.id.btn_mcodeQrcode);
        btn_mcodeQrcode.setOnClickListener(this);

        btn_sendReboot = findViewById(R.id.btn_sendReboot);
        btn_sendReboot.setOnClickListener(this);

        btn_openPlayer = findViewById(R.id.btn_openPlayer);
        btn_openPlayer.setOnClickListener(this);

        btn_closePlayer = findViewById(R.id.btn_closePlayer);
        btn_closePlayer.setOnClickListener(this);

        //更新播放器
        btn_updatePlayer = findViewById(R.id.btn_updatePlayer);
        btn_updatePlayer.setOnClickListener(this);

        //更新光传App
        btn_updateSpsApp = findViewById(R.id.btn_updateSpsApp);
        btn_updateSpsApp.setOnClickListener(this);

        //开启ADB
        btn_openADB = findViewById(R.id.btn_openADB);
        btn_openADB.setOnClickListener(this);

        txt_onhours = findViewById(R.id.txt_onhours);
        txt_onminutes = findViewById(R.id.txt_onminutes);
        btn_closeOnTime = findViewById(R.id.btn_closeOnTime);
        btn_closeOnTime.setOnClickListener(this);
        tv_result = findViewById(R.id.tv_result);



    }


    private void loadData() {
        mainPresenter = new MainPresenter(this,this);
        dbHelper = new DBHelper(this);
//        mlogDao = new MachineLogDao(this);
//        downloadLogDao = new DownloadLogDao(this);

        machineCacheInfo = MachineCacheInfo.getInstance(this);
        if (StringUtils.isEmpty(machineCacheInfo.getMcode())) {

            String code = AppTools.getDeviceId(MainActivity.this);
            code = Base64Utils.getBase64(code);
            code = code.replace("=", "").toUpperCase();
            machineCacheInfo.setMcode(code);

            String versionName = AppTools.getSoftVersion(MainActivity.this).versionName;
            machineCacheInfo.setAppVersion(versionName);

            String createTime = DateUtil.dateFormatToStr(DateUtil.DATE_TIME_FORMAT2, new Date());
            machineCacheInfo.setCreateTime(createTime);
            machineCacheInfo.setMinutes(1);

            machineCacheInfo.setAdPath(BussConstant.DEFAULT_ADPATH);
            machineCacheInfo.setServerUrl(BussConstant.getUrl());

            if (StringUtils.isEmpty(machineCacheInfo.getCfgVersion())) {
                machineCacheInfo.setCfgVersion("1");
            }

            machineCacheInfo.writeToCache();

        }

        String cfgVersion = machineCacheInfo.getCfgVersion();

        cfgVersion = machineCacheInfo.getAppVersion() + "&" + cfgVersion;

        tv_cfgId.setText(cfgVersion);
        long versionCode = AppTools.getVersionCode(this);
        //String versionName = AppTools.getSoftVersion(MainActivity.this).versionName;
        String versionName = String.format("V%d.0", versionCode);
        txt_appVersion.setText(versionName);
        txt_mcode.setText(machineCacheInfo.getMcode());
        txt_adPath.setText(machineCacheInfo.getAdPath());
        txt_apiServer.setText(machineCacheInfo.getServerUrl());
        txt_minutes.setText(machineCacheInfo.getMinutes() + "");
        String ip = IpGetUtil.getIPAddress(this);
        txt_ip.setText(ip);
        mainPresenter.startHttpServer();
        String serverUrl = MicroHttpServer.getHttpServerUrl(this);
        local_server_address.setText(serverUrl);
        setWiFIBtnText();
        readFileInfo();
        mainPresenter.loadLocalFilesToJsonFile();
    }

    private class UsbCopyTask extends AsyncTask{
        private String usbStoragePath;

        public UsbCopyTask(String usbStoragePath) {
            this.usbStoragePath = usbStoragePath;
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            String msg = mainPresenter.copyUsbADSToMachine(usbStoragePath);
//            String usbAdsDir = usbStoragePath + BussConstant.USB_ADPATH;
            Message message = new Message();
            message.what = BussConstant.HANDLER_USB_ADS_COPYS;
            Bundle bundle = new Bundle();
            bundle.putCharSequence("msg", msg);
            message.setData(bundle);
            handler.handleMessage(message);
            return true;
        }
    }

    /**
     * 复制USB广告文件到广告目录
     */
    private void copyUsbADS() {
        String usbStoragePath = "/mnt/usb/sda1";
        String usbAdsDir = usbStoragePath + BussConstant.USB_ADPATH;
       File file = new File(usbAdsDir);
       if(!file.exists()){
           Log.e(TAG,String.format("U盘广告文件夹%s不存在，请确认是否已插上U盘或U盘中是否存在%s文件夹", usbAdsDir, BussConstant.USB_ADPATH));
           return;
       }
       new UsbCopyTask(usbStoragePath).execute();
    }

    private void setWiFIBtnText() {
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        boolean enabled = wifiManager.isWifiEnabled();
        if (enabled) {
            btn_wifi.setText("关闭WIFI");
            Toast.makeText(this, "已关闭WiFi", Toast.LENGTH_SHORT);
        } else {
            btn_wifi.setText("开启WIFI");
            Toast.makeText(this, "已开启WiFi", Toast.LENGTH_SHORT);
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_pullCfg) {
            pullNewCfg();
        } else if (id == R.id.btn_save) {
            saveCfg();
        }else if (id == R.id.btn_checkUpdate) {
            checkUpdate();
        }else if (id == R.id.btn_checkPlayerUpdate) {
            checkPlayerUpdate();
        } else if (id == R.id.btn_wifi) {//
            enableWiFi();
        } else if (id == R.id.btn_aDswitch) {
            switchAd();
        } else if (id == R.id.btn_apiTest) {
            testApi();
        } else if (id == R.id.btn_downLoadVedio) {
            downLoadVideo();
        } else if (id == R.id.btn_startService) {
            startService();
        } else if (id == R.id.btn_delDB) {
            delDB();
        } else if (id == R.id.btn_addAD) {
            sendBrodcastToPlayer(BussConstant.CMD_AD_ADD);
        } else if (id == R.id.btn_delAD) {
            sendBrodcastToPlayer(BussConstant.CMD_AD_DEL);
        } else if (id == R.id.btn_delLogs) {
            mainPresenter.delLogs();
        } else if (id == R.id.btn_delVideo) {
            delVideo();
        } else if (id == R.id.btn_sendMcode) { //发送机器串码
            sendMcode();
        } else if (id == R.id.btn_sendReboot) { //发送广播通知
            sendBrodcast();
        } else if (id == R.id.btn_closeOnTime) { //定时关机
            closeSysOnTime();
        }else if (id == R.id.btn_openPlayer) { //打开播放器
            openPlayerApp();
        }else if (id == R.id.btn_closePlayer) { //关闭播放器
            closePlayerApp();
        }else if (id == R.id.btn_updatePlayer) { //更新播放器
           tip("更新播放器未实现");
        }else if (id == R.id.btn_updateSpsApp) { //更新光传App
            tip("更新光传App未实现");
        }else if (id == R.id.btn_openADB) { //开启ADB
            openADB();
        }else if(id == R.id.btn_mcodeQrcode){  // 机器串码二维码
            this.openMcodeQrCodeModal();
        }
    }

    /**
     * 广告自动下载开关控制
     */
    private void switchAd() {
         if(AlarmReceiver.adSwitch){
             AlarmReceiver.adSwitch = false;
             btn_aDswitch.setText("自动下载已关闭");
         }else{
             AlarmReceiver.adSwitch = true;
             btn_aDswitch.setText("自动下载已打开");
         }
    }

    /**
     * 打开机器串码二维码弹窗
     * @Author Mr.Shaw
     * @Date 2020/7/6 11:59
     */
    private void openMcodeQrCodeModal(){
        final String mcode = this.txt_mcode.getText().toString();
        if(!StringHandler.isValidStr(mcode)){
            ToastAlert.showMsg("请输入机器串码！");
            return;
        }
        if(StringUtils.isEmpty(mcodeQrCodeModel) || !mcode.equals(this.oldMcodeForQrCode)){
            this.oldMcodeForQrCode = mcode;
            int size = 400;
            final String localIp = IpGetUtil.getIPAddress(this);
            JSONObject content = new JSONObject(){{
                put("mcode", mcode);
                put("ip", localIp);
            }};
            Bitmap bitmap = ZxingHelper.createQRCodeBitmap(content.toString(), size, size, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
            if(!StringHandler.isValidObj(bitmap)){
                ToastAlert.showMsg("二维码生成失败！请重试");
                return;
            }
            ImageView imageView = new ImageView(this);
            imageView.setImageBitmap(bitmap);
            imageView.setPadding(0, 30, 0,  30);
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setView(imageView);
            this.mcodeQrCodeModel = alertBuilder.create();
        }
        this.mcodeQrCodeModel.show();
    }

    /**
     * 检测更新
     */
    private void checkUpdate() {
      //  ToastAlert.init(this);
        mainPresenter.checkUpdate(true,new MainPresenter.ConfirmCallback() {
            @Override
            public void execute(AppVersionResult appVersionResult) {
                Message message = new Message();
                message.what = BussConstant.HANDLER_CHECK_UPDATE_CONFIRM;
                Bundle bundle = new Bundle();
                bundle.putSerializable("appVersionResult", appVersionResult);
                message.setData(bundle);
                handler.sendMessage(message);
            }
        });
    }


    /**
     * 议峰智播更新
     */
    private void checkPlayerUpdate() {
        String playerVersion = mainPresenter.getPlayerVersion();
        ToastAlert.showMsg(String.format("当前议峰智播版本号：V%s.0", playerVersion));
        mainPresenter.checkUpdate(false,new MainPresenter.ConfirmCallback() {
            @Override
            public void execute(AppVersionResult appVersionResult) {
                Message message = new Message();
                message.what = BussConstant.HANDLER_CHECK_UPDATE_CONFIRM;
                Bundle bundle = new Bundle();
                bundle.putSerializable("appVersionResult", appVersionResult);
                message.setData(bundle);
                handler.sendMessage(message);
            }
        });
    }

    private void confirmInstallApk(final AppVersionResult appVersionResult){
        //String oldVersionNum = AppTools.getVersionCode(this)+"";
        String oldVersionNum = appVersionResult.getOldVersionNum();
        String versionNum = appVersionResult.getVersionNum();
        String upContent = appVersionResult.getUpcontent();
        String content = String.format("%s。\n 确定将当前APP由 %s 版本升级到 %s 版本吗？", upContent,oldVersionNum, versionNum);
        ToastAlert.confirm(this,"App更新提示",content,new ToastAlert.DialogCallback(){
            @Override
            public void execute(String actionBtn) {
                if(!actionBtn.equals(ToastAlert.ACTIONBTN_OK)) return;
                showProgressDialog(appVersionResult);
                mainPresenter.downloadAPK(appVersionResult, handler);
            }
        });
    }

    private void showProgressDialog(AppVersionResult appVersionResult){
        String versionNum = appVersionResult.getVersionNum();
        String title = String.format("V%s.0 App 安装包下载", versionNum);
        String content = String.format("正在下载最新V%s.0版App，请稍后...", versionNum);
        progressDialog =  new ProgressDialog(MainActivity.this);//实例化ProgressDialog
        progressDialog.setMax(100);//设置最大值
        progressDialog.setTitle(title);//设置标题
        progressDialog.setIcon(R.mipmap.ic_launcher);//设置标题小图标
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置样式为横向显示进度的样式
        progressDialog.setMessage(content);
        progressDialog.incrementProgressBy(0);//设置初始值为0，其实可以不用设置，默认就是0
        progressDialog.setIndeterminate(false);//是否精确显示对话框，flase为是，反之为否
        //添加确定按钮
        //参数1 设置按钮样式
        //参数2，设置按钮文本
        //参数3，设置按钮监听事件
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this,"确认下载完毕！",Toast.LENGTH_SHORT).show();
            }
        });


        //是否可以通过返回按钮退出对话框
        progressDialog.setCancelable(true);
        progressDialog.show();//显示对话框
    }

    private void openADB(){
        String action = "com.mstar.android.dlp638.startadbd";
        Intent intent = new Intent(action);
        sendBroadcast(intent);
        Toast.makeText(this, "开启ADB命令成功!", Toast.LENGTH_SHORT).show();
    }

    /**
     * 关闭APP
     */
    private void closePlayerApp(){
        String file_md5 = com.base.common.util.file.FileUtil.getFileMD5("/mnt/sdcard/yf/ADSource/1.mp4");
        String eq_md5 = "9db9bdedaafe0975938efa6abc23e3f3";
        ToastAlert.showMsg("file_md5="+file_md5+", isSame = "+(file_md5.equals(eq_md5)));
        openADB();
        String packageName = "com.media.yiti.ytplayer";
        ActivityManager activityMgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        activityMgr.killBackgroundProcesses(packageName);
       // activityMgr.killPackageProcessesLocked(packageName);
        tip("关闭PlayerApp 成功!");
        if(1==1) return;
        String[] cmdArr = {
               // "adb shell"//,
               // "ps"
                "su",
               // "am force-stop "+pkAge
        };
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand(cmdArr, false);
        String errorMsg = commandResult.errorMsg;
        String successMsg = commandResult.successMsg;
        if(!StringUtils.isEmpty(errorMsg)){
            tip("关闭PlayerApp 失败，原因："+errorMsg+"!");
        }else{
            Log.i(TAG, successMsg);
            tip("关闭PlayerApp 成功!");
        }

    }

    /**
     * 打开APP
     */
    private void openPlayerApp(){
        //String pkAge = "com.media.yiti.ytplayer";
        String pkAge = PACKAGE_YF_PLAYER_APP;
        boolean isInstalled = AppTools.isAppInstalled(this, pkAge);
        tip("PlayerApp "+(isInstalled?"已安装":"未安装")+"!");
        if(!isInstalled) return;
        boolean isOpen = AppTools.openPackage(this,pkAge);
        tip("打开PlayerApp "+(isOpen?"成功":"失败")+"!");
    }

    /**
     * 定时关机
     * com.example.playmedia.time
     * powerauto  = 1,0
     * poweroff = 0*256+5
     */
    private void closeSysOnTime(){
        //点击的时候发送一条广播出去
        int poweroff = -1;
        String onhours = "0";
        if(null != txt_onhours.getText()){
            onhours = txt_onhours.getText().toString();
            if(StringUtils.isEmpty(onhours)) onhours = "0";
            poweroff = Integer.parseInt(onhours) * 256;
        }
        String onminutes = "0";
        if(null != txt_onminutes.getText()){
            onminutes = txt_onminutes.getText().toString();
            if(StringUtils.isEmpty(onminutes)) onminutes = "0";
            if(poweroff == -1){
                poweroff = Integer.parseInt(onminutes);
            }else{
                poweroff += Integer.parseInt(onminutes);
            }
        }
        Log.e(TAG, "poweroff="+ poweroff);
        Intent intent = new Intent("com.example.playmedia.time");
        intent.putExtra("powerauto", 1);
        intent.putExtra("poweroff", poweroff);
        sendBroadcast(intent);
        Toast.makeText(this, "将于"+onhours+"小时"+onminutes+"分后关机", Toast.LENGTH_SHORT).show();
    }

    private void sendBrodcastToPlayer(int cmd){
        //点击的时候发送一条广播出去
        mainPresenter.notifyADAction(cmd);
        String actionName = (cmd == BussConstant.CMD_AD_ADD) ? "添加广告" : "删除广告";
        Toast.makeText(this, String.format("[%s]通知发送完成", actionName), Toast.LENGTH_SHORT).show();
    }


    private void sendBrodcast(){
        //点击的时候发送一条广播出去
        Intent intent = new Intent("com.amlogic.projector.lightswitch");
        sendBroadcast(intent);
        Toast.makeText(this, "通知发送完成", Toast.LENGTH_SHORT).show();
    }

    /**
     * 从服务器拉取最新配置
     */
    private void pullNewCfg() {
        if (null == txt_apiServer.getText()) {
            Toast.makeText(this, "API地址不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        String apiServer = txt_apiServer.getText().toString();
        String url = apiServer + UrlConstantAPI.MCONFIG_PULL;
        this.mainPresenter.bussFlag = BussConstant.BUSS_FLAG_1; //获取机器配置
        mainPresenter.getMachineCfg(url);
    }


    /**
     * 发送机器串码
     */
    private void sendMcode() {
        String apiServer = txt_apiServer.getText().toString();
        String mcode = txt_mcode.getText().toString();
        if (!StringHandler.isValidStr(apiServer)) {
            Toast.makeText(this, "API地址不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringHandler.isValidStr(mcode)) {
            Toast.makeText(this, "机器串号不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        final String url = apiServer + UrlConstantAPI.UNIME_SAVE;
        //
        mainPresenter.bussFlag = BussConstant.BUSS_FLAG_3;
        mainPresenter.sendMcode(url,mcode);
    }

    private void delVideo() {
        FileUtil.deleteDirectory(machineCacheInfo.getAdPath());
        tip(machineCacheInfo.getAdPath());
    }



    private void delDB() {
        dbHelper.dropDB();
    }

    private void startService() {
        Intent intent = new Intent(this, TaskService.class);
        startService(intent);
        tip("TaskService 服务开启成功!");
    }

    //视频下载
    //com.gx.tomplayer/.TomPlayerActivity
    private void downLoadVideo() {
        mainPresenter.bussFlag = BussConstant.BUSS_FLAG_4;
        mainPresenter.getAD();
    }

    public void openApp(String packageName) {
        try {
            Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "没有安装" + packageName, Toast.LENGTH_LONG).show();
        }
    }

    private void testApi() {
        if (null == txt_apiServer.getText()) {
            Toast.makeText(this, "API地址不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        final Context context = this;
        final String apiServer = txt_apiServer.getText().toString() + UrlConstantAPI.SERVIER_TEST;
        mainPresenter.bussFlag = BussConstant.BUSS_FLAG_2;
        mainPresenter.test(apiServer);
    }

    private void tip(final String msg) {
        tip(msg , null);
    }
    private void tip(final String msg, final HandlerCallback callback) {
        final Context context = this;

        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                if(null != callback) callback.execute(msg);
                if (msg.equals("文件下载成功")) {
                    readFileInfo();
                }
            }
        });
    }

    private void readFileInfo(){
        String adPath = txt_adPath.getText().toString();
        File file = new File(adPath);
        String[] list = file.list();
        StringBuilder sbContent = new StringBuilder();

        if (null != list && list.length > 0) {
            sbContent.append("共"+list.length+"个视频文件\n");
            for (String filePath : list) {
                sbContent.append(filePath).append("\n");
            }
        }else{
            sbContent.append("共0个视频文件");
        }
        tv_result.setText(sbContent.toString());
        ToastAlert.showMsg(sbContent.toString());
        //tipByLooper(sbContent.toString());
    }

    //保存修改的配置信息
    private void saveCfg() {
        if (null == txt_apiServer.getText()) {
            Toast.makeText(this, "API地址不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (null == txt_adPath.getText()) {
            Toast.makeText(this, "广告文件路径不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (null == txt_minutes.getText()) {
            Toast.makeText(this, "轮询时间不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }

        machineCacheInfo.setServerUrl(txt_apiServer.getText().toString());
        machineCacheInfo.setAdPath(txt_adPath.getText().toString());
        machineCacheInfo.setMinutes(Integer.parseInt(txt_minutes.getText().toString()));
        machineCacheInfo.writeToCache();
        Toast.makeText(this, "配置保存成功！", Toast.LENGTH_LONG).show();
    }



    /**
     * 开启关闭WIFI
     */
    private void enableWiFi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        } else {
            wifiManager.setWifiEnabled(true);
        }
    }

    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);

        } else {
            Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "checkPermission: 已经授权！");
        }
    }

    private void updateUICfgByPull(Message msg) {
        Bundle bundle = msg.getData();
        String appVersion = bundle.getString("appVersion");
        String adPath = bundle.getString("adPath");
        String serverUrl = bundle.getString("serverUrl");
        String minutes = bundle.getString("minutes");
        txt_appVersion.setText(appVersion);
        txt_adPath.setText(adPath);
        txt_apiServer.setText(serverUrl);
        txt_minutes.setText(minutes);
        Toast.makeText(MainActivity.this, "从服务器获取机器最新配置成功!", Toast.LENGTH_LONG).show();
    }


    private void setUI2Vals(){
        String cfgVersion = machineCacheInfo.getCfgVersion();
        String appVersion = machineCacheInfo.getAppVersion();
        cfgVersion = appVersion + "&" + cfgVersion;
        tv_cfgId.setText(cfgVersion);
        txt_appVersion.setText(AppTools.getSoftVersion(MainActivity.this).versionName);
        txt_adPath.setText(machineCacheInfo.getAdPath());
        txt_apiServer.setText(machineCacheInfo.getServerUrl());
        txt_minutes.setText(machineCacheInfo.getMinutes() + "");
    }


    @Override
    public void success(int flag, JSONObject result) {
        invokeByBussFlag(flag, result);
    }

    @Override
    public void failure(int flag, JSONObject result) {
        invokeByBussFlag(flag, result);
    }

    private void invokeByBussFlag(int flag, JSONObject result){
        switch (flag){
            case BussConstant.BUSS_FLAG_1:{ //拉取配置

                Boolean success = result.getBoolean("success");
                String msg = result.getString("msg");
                String serverUrl = result.getString(BussConstant.SERVER_URL_KEY);
                String tip = "从服务器：["+serverUrl+"]拉取配置成功！";
                if(!success){
                    tip = "从服务器：["+serverUrl+"]拉取配置失败，原因：["+msg+"]";
                }
                tip(tip, new HandlerCallback(){
                    @Override
                    public void execute(String msg) {
                        setUI2Vals();
                    }
                });
                break;
            }case BussConstant.BUSS_FLAG_2:{ //服务器连网测试
                Boolean success = result.getBoolean("success");
                String serverUrl = result.getString(BussConstant.SERVER_URL_KEY);
                String msg = result.getString("msg");
                String tip = "服务器地址：["+serverUrl+"]连网测试成功！";
                if(!success){
                    tip = "服务器地址：["+serverUrl+"]连网测试失败，原因：["+msg+"]";
                }
                tip(tip);
                break;
            }case BussConstant.BUSS_FLAG_3:{ //机器串码
                Boolean success = result.getBoolean("success");
                String serverUrl = result.getString(BussConstant.SERVER_URL_KEY);
                String msg = result.getString("msg");
                String tip = "成功发送串号到云端系统!";;
                if(!success){
                    tip = "无法通过：["+serverUrl+"]连发送串号到云端系统，原因：["+msg+"]";
                }
                tip(tip);
                break;
            }case BussConstant.BUSS_FLAG_4:{ //广告下载
                Boolean success = result.getBoolean("success");
                String serverUrl = result.getString(BussConstant.SERVER_URL_KEY);
                String msg = result.getString("msg");
                String tip = "成功]获取广告资源数据!";;
                if(!success){
                    tip = "无法通过：["+serverUrl+"]获取广告资源数据，原因：["+msg+"]";
                }
                tip(tip);
                break;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainPresenter.stopHttpServer();
    }

    /**
     * 回调接口
     */
    interface HandlerCallback{
        void execute(String msg);
    }
}